/**
 * @Date 2023-02-04 18:30:07
 * @Remark
 */

// react
import React, { useEffect, useState } from "react";
// lib
import { Tag, Dropdown } from "antd";
import { MenuOutlined, MoreOutlined } from "@ant-design/icons";
import { useLocation, useNavigate } from "react-router-dom";
import BetterScroll from "better-scroll";
import { useTitle } from "react-use";
import { sortBy } from "lodash-es";
// scroll
// components & widget
// style
import "./component.scss";
// config
import { APP_SETTING } from "config/setting";
import { ROUTE_MAIN_VIEW } from "project/config";
// script & methods & public
// store
import { observer } from "mobx-react";
import { appState } from "state/global";
// controller
import { completeLink, getCodeFromPath } from "routes/format";
import { getMenuListFromRoutes } from "routes/logic";
// interface
// 其它

let bs: BetterScroll | null = null;

function initScroll() {
  bs = new BetterScroll(".scroll-wrapper", {
    scrollX: true,
    scrollY: false,
    bounce: false,
    scrollbar: true,
    click: true,
    mouseWheel: {
      speed: 20,
    },
  });
}

// 使用pathname获得对应的menu
export function getMenuByPath(path: string) {
  let result: AppMenu | undefined = undefined;
  const code = getCodeFromPath(path);
  const menus = getMenuListFromRoutes();

  const menuList = menus.filter((el) => {
    return code.includes(el.key as string);
  });
  if (menuList.length > 1) {
    const sortMenus = sortBy(menuList, (el: any) => {
      return (el.key as string).length;
    });
    result = sortMenus[sortMenus.length - 1];
  } else {
    result = menuList[0];
  }
  // 拦截路径
  if (result) {
    result.key = code;
    result.url = path;
  }
  return result;
}

// 生成浏览器头部标题
function createTitle(title?: string) {
  const fullTitle = title
    ? `${title} - ${APP_SETTING.APP_NAME}`
    : APP_SETTING.APP_NAME;
  return fullTitle;
}

function RoutesTagGroup() {
  const location = useLocation();
  const navigate = useNavigate();

  const homePath = completeLink(ROUTE_MAIN_VIEW);
  const pathname = location.pathname;
  const menu = getMenuByPath(pathname);
  const tags = appState.getTagGroup();

  const [visible, setVisible] = useState(false);

  // 设置浏览器标题
  useTitle(createTitle(menu?.label));

  useEffect(() => {
    // 首先添加首页仪表盘的标签
    const homeTag = getMenuByPath(homePath);
    appState.addTag(homeTag);
    // 初始化滚动
    initScroll();
    return () => {
      appState.delTagOther();
    };
  }, [homePath]);

  useEffect(() => {
    // 添加对应页面的标签
    appState.addTag(getMenuByPath(pathname));

    // 延迟刷新计算新滚动
    setTimeout(() => {
      if (bs) {
        bs.refresh();
      }
    }, 100);
    return () => {
      //
    };
  }, [pathname]);

  function isActive(tag: AppMenu) {
    return tag.url === pathname;
  }

  function toLastView() {
    const lastView = appState.getTagGroup().slice(-1)[0];
    const to = lastView ? lastView.url : homePath;
    navigate(to);
  }

  return (
    <div className="routes-tag-wrapper">
      <div className="routes-tag-group scroll-wrapper">
        <div className="scroll-content">
          {tags.map((tag) => {
            const TagIcon = tag.icon || MenuOutlined;

            return (
              <Tag
                style={{
                  height: "26px",
                  lineHeight: "24px",
                  cursor: "pointer",
                }}
                key={tag.key}
                icon={<TagIcon />}
                color={tag.url === pathname ? "#1677ff" : undefined}
                closable={tag.key !== ROUTE_MAIN_VIEW}
                onClick={() => {
                  navigate(tag.url);
                }}
                onClose={() => {
                  appState.delTag(tag);
                  if (isActive(tag)) {
                    toLastView();
                  }
                }}
              >
                {tag.label}
              </Tag>
            );
          })}
        </div>
      </div>
      <Dropdown
        menu={{
          items: [
            {
              label: (
                <span
                  onClick={() => {
                    if (menu) {
                      appState.delTag(menu);
                      if (isActive(menu)) {
                        toLastView();
                      }
                    }
                  }}
                >
                  关闭当前标签页
                </span>
              ),
              key: "0",
            },
            {
              label: (
                <span
                  onClick={() => {
                    if (menu) {
                      appState.delTagOther(menu);
                    }
                  }}
                >
                  关闭其它标签页
                </span>
              ),
              key: "1",
            },
            {
              label: (
                <span
                  onClick={() => {
                    appState.delTagOther();
                    toLastView();
                  }}
                >
                  关闭所有标签页
                </span>
              ),
              key: "2",
            },
          ],
        }}
        open={visible}
        onOpenChange={(val) => {
          setVisible(val);
        }}
      >
        <span className="routes-tag-menu">
          <MoreOutlined />
          操作
        </span>
      </Dropdown>
    </div>
  );
}

export default observer(RoutesTagGroup);
